package com.moon.controller;


import com.aliyun.oss.OSSClient;
import com.moon.pojo.Result;
import com.moon.utils.AliYunOSSClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class FileUploadController {

    @Autowired
    private AliYunOSSClient ossClient;

    @PostMapping("/upload")
    public Result uploadWithOOS(MultipartFile file) throws Exception {
        log.info("上传文件：{}", file);
        if (!file.isEmpty()) {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
            // 上传文件
            String url = ossClient.upload(file.getBytes(), uniqueFileName);
            return Result.success(url);
        }
        return Result.error("上传失败");
    }

    @PostMapping("/upload02")
    public Result upload(String name, Integer age, MultipartFile file){
        log.info("name={},age={},file={}", name, age, file);

        UUID uuid = UUID.randomUUID();
        String originalFilename = file.getOriginalFilename();
        String newFileName = uuid + originalFilename;
        // 获取项目根路径
        String uploadDir = System.getProperty("user.dir") + File.separator + "files";
        try {
            file.transferTo(new File(uploadDir + File.separator + newFileName));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }
        return Result.success();
    }
}
